import { observable, action, autorun, toJS } from 'mobx';
import { WeaTools, WeaLocaleProvider } from 'ecCom';
import { message, Modal } from 'antd';
import * as Apis from '../apis/highSeas';

const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;

export default class ConditionDialogStore {
    @observable inited = false;
    @observable formInfo = {};
    refObj = {};

    @action
    init = (params, conditionSaveCallBack, conditionCancelCallBack) => {
      const customerScope = params.customerScope;
      const mainTablename = params.mainTablename;
      this.inited = true;
      // this.visible = false;
      this.conditionInfo.fieldOptions = [];
      this.conditionField = {};
      this.conditionInfo.conditiontype = '1';
      this.root = {};
      this.conditionInfo.conditionsql2 = '';
      const fieldParams = { mainTablename };
      Apis.getHighSeasInfo('getConditionfield', fieldParams).then((data) => {
        if (data.fieldOptions) {
          this.conditionInfo.fieldOptions = data.fieldOptions;
        }

        if (data.conditionField) {
          this.conditionField = data.conditionField;
        }
        if (data.dbtype) {
          this.dbtype = data.dbtype;
        }
      });

      this.conditionSaveCallBack = conditionSaveCallBack;
      this.conditionCancelCallBack = conditionCancelCallBack;
      this.conditionInfo.mainTablename = mainTablename;
      if (customerScope && customerScope.param) {
        const param = customerScope.param;
        if (param.conditiontype) this.conditionInfo.conditiontype = param.conditiontype;
        if (param.conditiontype == '1') {
          if (param.rootdata) {
            this.root = param.rootdata;
            this.getShowSql();
          }
        } else {
          const Base64 = WeaTools.Base64;
          const sql = Base64.decode(param.conditionsql);
          this.conditionInfo.conditionsql2 = sql;
        }
      }
    }


    @action
    setFormInfo = (params) => {
      this.formInfo = { ...this.formInfo, ...params };
    }


    @observable conditionInfo = {
      conditionsql: '',
      conditionsql2: '',
      conditiontext: '',
      conditiontype: '1',
      count: 1,
      detailTables: [],
      mainTablename: 'CRM_CustomerInfo',
      fieldOptions: [],
    };

    @observable type = '';// 类型  modeRight：权限条件
    @observable objid = '';// 所属对象的id
    @observable visible = false;
    @observable mask = true;
    @observable dialogLoading = false;
    @observable conditions = {};
    @observable conditionParam={};// 条件参数
    @observable initParam={};// 初始化参数
    @observable conditionField={};
    @observable relationtypeOptions =[];

    @observable fieldRecord={};
    @observable relation='4';// 等于
    @observable targetValue='';// 值
    @observable targetValueSpan='';// 显示名称
    @observable ismodified='0';// 是否修改了
    @observable dbtype='sqlserver';// 数据库类型

    @observable root={};
    @observable selectedItemKey=[];
    @observable editArr=[];// 处于编辑状态的数据
    @observable selectedItemParentNode='';
    @observable ruleSql='';
    @observable ruleSqlText='';
    @observable isShowSql=false;
    @observable contentHeight;
    @observable conditionSaveCallBack;
    @observable conditionCancelCallBack;
    @observable toShowErrorSql;
    @observable dialogName='';// 用来解决存在多个dialog的时候，同时打开多个
    @observable isNeedClose=false;// 是否需要关闭dialog
    @observable isChange=false;// 顶部条件是否改变
    @observable checkButtonDisabled = false;// 检查sql按钮默认不置灰

    @action
    onSave=() => {
      const { conditiontype, conditionsql2 } = this.conditionInfo;
      const param = { type: this.type, objid: this.objid, conditiontype, operation: 'saveCondition' };
      const checkSQL = this.checkSQL;
      if (conditiontype == 1) {
        if (this.editArr.length > 0) {
          message.error(getLabel(384753, '存在字段处理编辑状态，请编辑好后再进行保存操作'));
          return;
        }
        if (this.isChange == true && this.targetValue != '') {
          // let doSaveCondition = this.doSaveCondition;
          Modal.confirm({
            title: getLabel(385010, '当前目标字段的值未添加到条件中，是否继续保存？'),
            onOk() {
              // doSaveCondition(param);
              // param.rootdata = this.root;
              // this.getShowSql();
              // let Base64 = WeaTools.Base64;
              // let sql = Base64.encode(this.ruleSql);
              // let sqlText = Base64.encode(this.ruleSqlText);
              // param.conditionsql = sql;
              // param.conditiontext = sqlText;
              checkSQL(param);
            },
            onCancel() {},
          });
        } else {
          // this.doSaveCondition(param);
          // param.rootdata = this.root;
          // this.getShowSql();
          // let Base64 = WeaTools.Base64;
          // let sql = Base64.encode(this.ruleSql);
          // let sqlText = Base64.encode(this.ruleSqlText);
          // param.conditionsql = sql;
          // param.conditiontext = sqlText;
          checkSQL(param);
        }
      } else {
        if (_.trim(formatMultiLang(conditionsql2)) == '') {
          for (const key in this.refObj) {
            if (key == 'sql_') {
              const domkeyRef = this.refObj[key];
              domkeyRef.showError();
              return;
            }
          }
          // message.error("sql"+getLabel(130807, "不能为空!"));
          // return;
        }
        // if(trim(conditionsql2)==""){
        //     message.error("sql"+getLabel(130806, "不能为空!"));
        //     return;
        // }
        // let Base64 = WeaTools.Base64;
        // let sql = Base64.encode(conditionsql2);
        // param.conditionsql = sql;
        checkSQL(param);
        // this.isNeedClose = false;
        // this.setFormInfo({customerScope:JSON.stringify({param})});
        // this.onCancel();

        // this.conditionSaveCallBack( this.formInfo);
      }
    }

    doSaveCondition=(param) => {
      // this.getShowSql();
      // if(this.ruleSql==""){
      //     message.error(getLabel(15364,"条件")+getLabel(130806, "不能为空!"));
      //     return;
      // }

      this.isNeedClose = false;
      this.setFormInfo({ customerScope: JSON.stringify({ param }) });
      this.onCancel();

      this.conditionSaveCallBack(this.formInfo);
    }

    deleteCondition=() => {
      const that = this;
      const param = { type: this.type, objid: this.objid, operation: 'deleteCondition' };
      this.isNeedClose = true;
      Modal.confirm({
        title: getLabel(84545, '确定清空所有条件？'),
        onOk() {
          that.setFormInfo({ customerScope: null });
          that.onCancel();
          that.root = {};
          that.ruleSql = '';
          that.ruleSqlText = '';

          that.conditionSaveCallBack(that.formInfo);
        },
        onCancel() {},
      });
    }

    checkSQL=(saveParam) => {
      // if(this.ismodified=="1"){
      //     message.error(getLabel(82692,"请先保存，再检测条件"));
      //     return;
      // }
      // this.toShowErrorSql = toShowErrorSql;
      // let param = {type:this.type,objid:this.objid,operation:"checkSQL"};
      this.getShowSql();

      // console.log(toJS(this.conditionInfo))
      // console.log(toJS(this.ruleSql))

      let sql = '';
      const conditiontype = this.conditionInfo.conditiontype;
      if (conditiontype == '1') {
        sql = this.ruleSql;
      } else {
        sql = this.conditionInfo.conditionsql2;
      }
      if (sql == '') {
        message.error(getLabel('387163', '没有添加条件，请检查！'));
        return;
      }
      const Base64 = WeaTools.Base64;
      sql = Base64.encode(sql);

      const params = { checkSQL: sql, operate: 'checkSQL', mainTablename: this.conditionInfo.mainTablename };
      this.checkButtonDisabled = true;
      Apis.getHighSeasInfo('doSaveForm', params).then((data) => {
        if (data.errflag) {
          message.error(data.errMsg);
        } else if (saveParam) {
          if (conditiontype == '1') {
            saveParam.rootdata = this.root;
            saveParam.conditiontext = Base64.encode(this.ruleSqlText);
          }
          saveParam.conditionsql = sql;
          this.doSaveCondition(saveParam);
        } else {
          message.success(getLabel('387162', '条件检测通过'));
        }
        this.checkButtonDisabled = false;
      });
    }

    @action
    getShowSql=() => {
      let sql = '';
      let sqlText = '';
      if (this.root.key && this.root.key > 0) {
        const obj = this.getSql(this.root, { sql: '', sqlText: '' });
        sql = obj.sql;
        sqlText = obj.sqlText;
      }
      this.ruleSql = sql;
      this.ruleSqlText = sqlText;
    }

    @action
    getSql=(item, { sql, sqlText }) => {
      const { isParent } = item;
      if (isParent) {
        const { datas, relationship } = item;
        let relation = 'AND';
        if (relationship == '0') {
          relation = 'OR';
        }
        for (let i = 0; i < datas.length; i++) {
          if (i > 0) {
            sql += ` ${relation} `;
            sqlText += ` ${relation} `;
          }
          if (datas.length > 1 && i == 0) {
            sql += '(';
            sqlText += '(';
          }
          const obj = this.getSql(datas[i], { sql: '', sqlText: '' });
          sql += obj.sql;
          sqlText += obj.sqlText;
          if (datas.length > 1 && i == datas.length - 1) {
            sql += ')';
            sqlText += ')';
          }
        }
      } else {
        const { compareopion, tablename, fieldname, htmltype, fieldtype, fieldvalue, fieldlabel, fieldtext } = item;
        let relationAndVal = '';
        let text = '';
        if (fieldvalue == 'null' && (htmltype == 5 || htmltype == 4)) { // select或者checkbox 框为null
          if (compareopion == 4) { // 等于
            relationAndVal = ' is null ';
          } else if (compareopion == 5) { // 不等于
            relationAndVal = ' is not null ';
          } else if (compareopion == 6) { // 包含
            relationAndVal = ' is null ';
          } else { // 不包含
            relationAndVal = ' is not null ';
          }
          text = relationAndVal;
          sql += `${tablename}.${fieldname} ${relationAndVal}`;
          sqlText += `${fieldlabel} ${text}`;
        } else if ((htmltype == 5 && fieldtype == 2) || (htmltype == '3' && (fieldtype == '17' || fieldtype == '18' || fieldtype == '37' || fieldtype == '57' || fieldtype == '65' || fieldtype == '135' || fieldtype == '152' || fieldtype == '162'
                || fieldtype == '166' || fieldtype == '168' || fieldtype == '170' || fieldtype == '184' || fieldtype == '194' || fieldtype == '257' || fieldtype == '261'
                || fieldtype == '269' || fieldtype == '278'))) {
          const fieldvaluevar = fieldvalue.split(',');
          if (compareopion == 6) { // 包含
            for (let i = 0; i < fieldvaluevar.length; i++) {
              if (i == 0) {
                if (this.dbtype == 'mysql') {
                  relationAndVal += ` concat(',',${tablename}.${fieldname},',') like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'oracle' || this.dbtype == 'db2') {
                  relationAndVal += ` ','||${tablename}.${fieldname}||',' like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'sqlserver') {
                  relationAndVal += ` ','+isnull(cast(${tablename}.${fieldname} as varchar(4000)),'')+',' like '%,${fieldvaluevar[i]},%'`;
                }
              } else {
                if (this.dbtype == 'mysql') {
                  relationAndVal += ` AND concat(',',${tablename}.${fieldname},',') like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'oracle' || this.dbtype == 'db2') {
                  relationAndVal += ` AND ','||${tablename}.${fieldname}||',' like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'sqlserver') {
                  relationAndVal += ` AND ','+isnull(cast(${tablename}.${fieldname} as varchar(4000)),'')+',' like '%,${fieldvaluevar[i]},%'`;
                }
              }
            }
            text = `${' like ' + "'%"}${fieldtext}%'`;
          } else if (compareopion == 7) { // 不包含
            for (let i = 0; i < fieldvaluevar.length; i++) {
              if (i == 0) {
                if (this.dbtype == 'mysql') {
                  relationAndVal += ` concat(',',${tablename}.${fieldname},',') not like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'oracle' || this.dbtype == 'db2') {
                  relationAndVal += ` ','||${tablename}.${fieldname}||',' not like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'sqlserver') {
                  relationAndVal += ` ','+isnull(cast(${tablename}.${fieldname} as varchar(4000)),'')+',' not like '%,${fieldvaluevar[i]},%'`;
                }
              } else {
                if (this.dbtype == 'mysql') {
                  relationAndVal += ` AND concat(',',${tablename}.${fieldname},',') not like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'oracle' || this.dbtype == 'db2') {
                  relationAndVal += ` AND ','||${tablename}.${fieldname}||',' not like '%,${fieldvaluevar[i]},%'`;
                }
                if (this.dbtype == 'sqlserver') {
                  relationAndVal += ` AND ','+isnull(cast(${tablename}.${fieldname} as varchar(4000)),'')+',' not like '%,${fieldvaluevar[i]},%'`;
                }
              }
            }
            text = `${' not like ' + "'%"}${fieldtext}%'`;
          } else {
            var isneedf = true;
            if (htmltype == 4) { // checkbox
              isneedf = false;
            } else if (htmltype == 1 && (fieldtype == 2 || fieldtype == 3)) { // 整数浮点数
              isneedf = false;
            } else if (htmltype == 5 && fieldtype == 2) {
              isneedf = true;
            } else if (htmltype == 5) { // select框
              isneedf = false;
            }

            let compareoptionStr = '';
            if (compareopion == '0') {
              compareoptionStr = '>';
            } else if (compareopion == '1') {
              compareoptionStr = '>=';
            } else if (compareopion == '2') {
              compareoptionStr = '<';
            } else if (compareopion == '3') {
              compareoptionStr = '<=';
            } else if (compareopion == '4') {
              compareoptionStr = '=';
            } else if (compareopion == '5') {
              compareoptionStr = '!=';
            } else if (compareopion == '100') {
              compareoptionStr = 'like';
            }
            if (isneedf) {
              relationAndVal = `${compareoptionStr} '${fieldvalue}'`;
            } else {
              relationAndVal = `${compareoptionStr} ${fieldvalue}`;
            }
            text = `${compareoptionStr} '${fieldtext}'`;
          }
          if (compareopion == 6 || compareopion == 7) {
            sql += `( ${relationAndVal} )`;
          } else {
            sql += `${tablename}.${fieldname} ${relationAndVal}`;
          }
          sqlText += `${fieldlabel} ${text}`;
        } else {
          let fieldvalueObj = '';
          if (fieldtype == '256') { // 自定义树形
            const fieldvaluevar = fieldvalue.split(',');
            for (let i = 0; i < fieldvaluevar.length; i++) {
              fieldvalueObj += `'${fieldvaluevar[i]}',`;
            }
            fieldvalueObj = fieldvalueObj.substring(0, fieldvalueObj.length - 1);
          }
          if (compareopion == 6) { // 包含
            relationAndVal = `${' like ' + "'%"}${fieldvalue}%'`;
            text = `${' like ' + "'%"}${fieldtext}%'`;
          } else if (compareopion == 7) { // 不包含
            relationAndVal = ` not like '%${fieldvalue}%'`;
            text = `${' not like ' + "'%"}${fieldtext}%'`;
          } else if (compareopion == 8) { // 属于
            if (fieldtype == '256') {
              relationAndVal += ` in (${fieldvalueObj})`;
            } else {
              relationAndVal += ` in (${fieldvalue})`;
            }
            text = `${' in ' + '('}${fieldtext})`;
          } else if (compareopion == 9) { // 不属于
            if (fieldtype == '256') {
              relationAndVal += ` not  in (${fieldvalueObj})`;
            } else {
              relationAndVal += ` not  in (${fieldvalue})`;
            }
            text = `${' not  in ' + '('}${fieldtext})`;
          } else if (compareopion == 10) { // 属于(含下级)
            relationAndVal += ` in (${fieldvalue})`;
            text = `${getLabel(82763, '属于(含下级)')}(${fieldtext})`;
          } else if (compareopion == 11) { // 属于(不含下级)
            relationAndVal += ` not  in (${fieldvalue})`;
            text = `${getLabel(82764, '不属于(含下级)')}(${fieldtext})`;
          } else {
            var isneedf = true;
            if (htmltype == 4) { // checkbox
              isneedf = false;
            } else if (htmltype == 1 && (fieldtype == 2 || fieldtype == 3 || fieldtype == 4)) { // 整数浮点数金额转换
              isneedf = false;
            } else if (htmltype == 5) { // select框
              isneedf = false;
            }

            let compareoptionStr = '';
            if (compareopion == '0') {
              compareoptionStr = '>';
            } else if (compareopion == '1') {
              compareoptionStr = '>=';
            } else if (compareopion == '2') {
              compareoptionStr = '<';
            } else if (compareopion == '3') {
              compareoptionStr = '<=';
            } else if (compareopion == '4') {
              compareoptionStr = '=';
            } else if (compareopion == '5') {
              compareoptionStr = '!=';
            } else if (compareopion == '100') {
              compareoptionStr = 'like';
            }

            if (htmltype == 2 && fieldtype == 1 && this.dbtype == 'sqlserver') { // 多行文本
              relationAndVal = ` isnull(cast(${tablename}.${fieldname} as varchar(4000)),'') ${compareoptionStr} '${fieldvalue}'`;
            } else if (!fieldvalue) { // 添加可以为空
              let ifnull = 'is null';
              if (compareopion == '4') {
                ifnull = 'is null';
              } else if (compareopion == '5') {
                ifnull = 'is not null';
              }
              if (isneedf) {
                relationAndVal = `${compareoptionStr} '${fieldvalue}'` + ` or ${tablename}.${fieldname} ${ifnull}`;
              } else {
                relationAndVal = ifnull;
              }
            } else if (isneedf) {
              relationAndVal = `${compareoptionStr} '${fieldvalue}'`;
            } else {
              relationAndVal = `${compareoptionStr} ${fieldvalue}`;
            }
            text = `${compareoptionStr} '${fieldtext}'`;
          }
          if (!fieldvalue) { // 添加可以为空
            if (htmltype == 2 && fieldtype == 1 && this.dbtype == 'sqlserver') { // 多行文本
              sql += relationAndVal;
            } else {
              var isneedf = true;
              if (htmltype == 4) { // checkbox
                isneedf = false;
              } else if (htmltype == 1 && (fieldtype == 2 || fieldtype == 3)) { // 整数浮点数
                isneedf = false;
              } else if (htmltype == 5) { // select框
                isneedf = false;
              }
              if (isneedf) {
                sql += '(';
              }
              sql += `${tablename}.${fieldname} ${relationAndVal}`;
              if (isneedf) {
                sql += ')';
              }
            }
          } else if (htmltype == 2 && fieldtype == 1 && this.dbtype == 'sqlserver') { // 多行文本
            sql += relationAndVal;
          } else {
            sql += `${tablename}.${fieldname} ${relationAndVal}`;
          }

          sqlText += `${fieldlabel} ${text}`;
        }
      }
      return { sql, sqlText };
    }

    getRelationArr=(relationtype, type) => {
      let arr = new Array();
      if (relationtype == '1') {
        arr = [{
          key: '4',
          showname: getLabel(327, '等于'),
        }, {
          key: '5',
          showname: getLabel(15506, '不等于'),
        }, {
          key: '6',
          showname: getLabel(346, '包含'),
        }, {
          key: '7',
          showname: getLabel(15507, '不包含'),
        }];
      } else if (relationtype == '2') {
        arr = [{
          key: '0',
          showname: getLabel(15508, '大于'),
        }, {
          key: '1',
          showname: getLabel(325, '大于或等于'),
        }, {
          key: '2',
          showname: getLabel(15509, '小于'),
        }, {
          key: '3',
          showname: getLabel(326, '小于或等于'),
        }, {
          key: '4',
          showname: getLabel(327, '等于'),
        }, {
          key: '5',
          showname: getLabel(15506, '不等于'),
        }];
      } else if (relationtype == '3') {
        if (type == '2') {
          arr = [{
            key: '6',
            showname: getLabel(346, '包含'),
          }, {
            key: '7',
            showname: getLabel(15507, '不包含'),
          }];
        } else {
          arr = [{
            key: '4',
            showname: getLabel(327, '等于'),
          }, {
            key: '5',
            showname: getLabel(15506, '不等于'),
          }];
        }
      } else if (relationtype == '4') {
        if (type == '17' || type == '18' || type == '37' || type == '57' || type == '65' || type == '135' || type == '152' || type == '162'
                || type == '166' || type == '168' || type == '170' || type == '184' || type == '194' || type == '257' || type == '261'
                || type == '269' || type == '278') {
          arr = [{
            key: '6',
            showname: getLabel(346, '包含'),
          }, {
            key: '7',
            showname: getLabel(15507, '不包含'),
          }];
        } else {
          arr = [{
            key: '4',
            showname: getLabel(327, '等于'),
          }, {
            key: '5',
            showname: getLabel(15506, '不等于'),
          }];
          if (type == '1' || type == '165' || type == '167' || type == '169' || type == '16' || type == '9'
                    || type == '7' || type == '8' || type == '24' || type == '161' || type == '256' || type == '87' || type == '292' || type == '270') {
            arr.push({
              key: '8',
              showname: getLabel(353, '属于'),
            },
            {
              key: '9',
              showname: getLabel(21473, '不属于'),
            });
          }
          if (type == '4' || type == '164') {
            arr.push({
              key: '8',
              showname: getLabel(353, '属于'),
            },
            {
              key: '9',
              showname: getLabel(21473, '不属于'),
            }, {
              key: '10',
              showname: getLabel(82763, '属于(含下级)'),
            }, {
              key: '11',
              showname: getLabel(82764, '不属于(含下级)'),
            },
            );
          }
        }
      }
      return arr;
    }

    @action
    onShow=() => {
      this.visible = true;
    }

    @action
    onCancel=() => {
      this.visible = false;
      this.fieldRecord = {};
      this.conditionCancelCallBack();
    }
}
